import grace from "../grace/index.js"
const config = require('config.js');

grace.http.config.baseURL = config.serviceUrl;
grace.http.config.timeout = config.requestionTimeout;
//http发送请求前的预处理
grace.http.interceptors.request.use((request) => {
  if (config.isDebug) {
    console.info("interceptors.request", request.baseURL + request.url, request.body);
  }
  if (request.method == 'GET' && request.body){
    request.body['_fmt'] = new Date().getTime();
  }
  if (request.body){
    request.body['api_token'] = wx.getStorageSync('api_token');
  }
  if (request.url != 'api/cart/list' || request.url != "api/cart/statistics" || request.url != "api/user/applet_login"){
    let submitTitle = '正在提交...';
    if (request.url == 'api/user/applet_login'){
      submitTitle='正在登录中...';
    }
    if (request.method == 'POST'){
      wx.showToast({
        title: submitTitle,
        icon: 'loading',
        duration: 2000
      })
    }else{
      wx.showNavigationBarLoading();
    }
  }
});
//http请求成功的预处理
grace.http.interceptors.response.use(
  (response) => {
    wx.hideNavigationBarLoading()
    wx.stopPullDownRefresh();
    wx.hideToast();
    return response.data;
  }, (err) => {
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
    wx.hideToast();
    if (err.status == 1) {//请求超时
      
    } else if (err.status == 403) {//登录失效
      if (wx.getStorageSync('api_token')){
        wx.removeStorageSync('api_token');
        grace.bus.$emit("usre_logout_success");
      }
    }else if (err.status == 400) {//常规错误
      try{
        var res = JSON.parse(err.engine.response);
        var message = res.message;
        if (message) {
          wx.showToast({
            title: message,
            icon: 'none'
          })
        }
      }catch(e){
        console.err('error');
      }
    }
    return err;
  }
)
var page = grace.page;
grace.page = function (ob) {
  grace.mixin(ob, {
    data:{
      userInfo:null,
      showAuthBtn:false,
      store_id:0,
      logining:false,//登录中
      isIpx: getApp().globalData.isIpx
    },
    onLoad(options) {
      wx.showNavigationBarLoading();
      let params = options[0][0];
      if (params) {
        //来源一:from_store
        let from_store_id = 0;
        if (params['from_store']) {
          from_store_id = params['from_store'];
        }
        //来源二：扫描二维码
        let url_query = params['q'];
        if (url_query) {
          let url = decodeURIComponent(url_query);
          let from_store = url.substring(url.lastIndexOf("/") + 1);
          if (from_store) {
            from_store_id = from_store;
          }
        }
        if (from_store_id){
          //保存来源门店，避免丢失
          wx.setStorageSync('from_store_id', from_store_id);
        }

        //绑定门店
        let token = wx.getStorageSync('api_token');
        if (token && from_store_id) {
          this.bindStore(from_store_id);
          this.$data.store_id = from_store_id;
        }
      }
     
      //登陆失效，重新登录
      grace.bus.$on("usre_logout_success", (data) => {
        let pages    = getCurrentPages();
        let currPage = pages[pages.length - 1];//当前页面
        if (currPage['route'] != 'pages/auth/auth') {
          let params = '';
          for (let name in currPage['options']){
            params = params + name+'=' + currPage['options'][name]
          }
          wx.setStorageSync('current_page', currPage['route'] + '?' + params);
          wx.redirectTo({
            url: '/pages/auth/auth',
          })
        }
      });
      
    },
    onShow:function(){
      let pages = getCurrentPages();
      let currPage = pages[pages.length - 1];//当前页面
      console.log('onShow', currPage);
    },
    bindStore: function (store_id){
      if (parseInt(store_id) > 0){
        this.$http.post('api/user/binding_store', { store_id: store_id });
        wx.setStorageSync('current_store', store_id);
      }
    },
    toast(msg, icon) {
      var _icon = icon || 'none';
      wx.showToast({
        title: msg,
        icon: _icon,
        duration: 2000
      })
    },
    //日志
    log(msg){
      if (config.isDebug) {
        console.log(msg);
      }
    },
    setUserInfo(user){
      wx.setStorageSync('api_token',user.api_token);
      wx.setStorageSync('user_id', user.user_id);
      wx.setStorageSync('mobile_phone', user.mobile_phone);
      wx.setStorageSync('real_name', user.real_name);
      wx.setStorageSync('nickname', user.nickname);
      wx.setStorageSync('headimgurl', user.headimgurl);
      wx.setStorageSync('from_store', user.from_store);
      wx.setStorageSync('current_store', user.current_store);
      wx.setStorageSync('card_number', user.card_number);
      wx.setStorageSync('unionid', user.unionid);
      wx.setStorageSync('card_name', user.card_name);
    }
  })
  //创建页面
  page.call(grace, ob);
}
export default grace;